#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
RESOURCES_DIR="$DIR/../Resources"

# Log output for troubleshooting
exec > ~/Library/Logs/ParcelGunPro.log 2>&1

echo "=== Launching ParcelGun Pro ==="
echo "Working directory: $DIR"

# Find Python 3
PYTHON=""
for p in /usr/local/bin/python3 /opt/homebrew/bin/python3 /usr/bin/python3 $(which python3 2>/dev/null); do
    if [ -x "$p" ]; then
        PYTHON="$p"
        break
    fi
done

if [ -z "$PYTHON" ]; then
    osascript -e 'display alert "Python 3 Required" message "ParcelGun Pro requires Python 3. Please install Python from https://www.python.org or run: brew install python" as critical'
    exit 1
fi

echo "Using Python: $PYTHON"

# Ensure pip dependencies are installed in user space or virtual env
"$PYTHON" -c "import flask, qrcode, PIL" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "Installing required packages..."
    "$PYTHON" -m pip install -r "$RESOURCES_DIR/requirements.txt" 2>/dev/null
fi

exec "$PYTHON" "$RESOURCES_DIR/server.py"
